<template>
	<div class="map-container">
		<CityCascader v-model="data.city" class="mb10" />
		<el-input v-model="data.locationDetail" placeholder="输入详细地址" class="mb10" />
		<el-input v-model="data.coordDes" placeholder="" class="mb10">
			<template #append>
				<el-button type="primary" @click="getCoord">自动解析</el-button>
			</template>
		</el-input>

		<div id="container"></div>
	</div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { ElMessage } from 'element-plus';
import CityCascader from '/@/components/cityCascader/index.vue';

const props = defineProps({
	modelValue: {
		type: Array,
		default: () => [],
	},
	keyWord: {
		type: String,
		default: '门店',
	},
});

const emits = defineEmits(['update:modelValue']);

let map: any = null;
let autoComplete: any = null;
let marker: any = null;
let infoWindow: any = null;
let init = true;

let data = ref({
	locationDetail: '',
	coordDes: '',
	city: '',
});

watch(
	() => props.modelValue,
	(val: any) => {
		val.coordDes = `当前${props.keyWord}的经度：${val.coord[0]}，纬度：${val.coord[1]}`;
		data.value = { ...val };

		if (init && val) {
			initMap(false, getCoord);
			init = false;
		}
	}
);

watch(
	() => data,
	(val) => {
		emits('update:modelValue', val);
	}
);

const getCoord = () => {
	if (!data.value.city || !data.value.locationDetail) {
		ElMessage.warning('请完善地址信息');
		return;
	}
	const keyword = data.value.locationDetail;
	//根据关键字进行搜索 keyword 为搜索的关键词
	autoComplete.setCity(data.value.city[1]);
	autoComplete.search(keyword, function (status, result) {
		if (result.info === 'OK') {
			const { location, name, district, address, tel } = result.tips[0].id ? result.tips[0] : result.tips[1];
			if (!location) {
				ElMessage.error(`未搜索到${props.keyWord}，请完善详细的地址信息`);
				return;
			}
			data.value.coord = [location.lng, location.lat];
			data.value.coordDes = `当前${props.keyWord}的经度：${location.lng}，纬度：${location.lat}`;
			emits('update:modelValue', data.value);
			// result为对应的匹配数据
			//搜索成功时，result 即是对应的匹配数据
			// 清除之前的标记
			const callback = () => {
				// map.clearMap();
				// // 将地图中心点设置为搜索结果的坐标
				map.setCenter(location);
				// 添加标记
				marker.setPosition(location);
				map.add(marker);
				map.setFitView(marker);
				// 添加信息窗
				var info = [];
				info.push(`<p class='input-item'>${name}</p></div></div>`);
				info.push(`<p class='input-item text-regular font12 mt5 mb5'>${district}${address}</p></div></div>`);
				if (tel) {
					info.push(`<p class='input-item text-regular font12'>电话 : ${tel}</p>`);
				}
				infoWindow.setContent(info.join(''));
				infoWindow.open(map, marker.getPosition());
			};
			map?.destroy();
			initMap(data.value.coord, callback);
		} else {
			ElMessage.error('未找到该地址');
		}
	});
};
const showInfoClick = (e) => {
	console.log(e);
};

const initMap = (center?: any, callback?: any) => {
	window._AMapSecurityConfig = {
		securityJsCode: import.meta.env.VITE_GD_MAP_SECRET_KEY,
	};
	const param = { resizeEnable: true };
	if (center) {
		param.center = center;
	}
	AMapLoader.load({
		key: import.meta.env.VITE_GD_MAP_KEY, // 申请好的Web端开发者Key，首次调用 load 时必填
		version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
		plugins: ['AMap.Geolocation', 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.ElasticMarker', 'AMap.InfoWindow'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
	})
		.then((AMap) => {
			map = new AMap.Map('container', param);
			autoComplete = new AMap.AutoComplete();
			//构造点标记
			marker = new AMap.Marker();
			infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) });
			map.on('click', showInfoClick);
			callback && callback();
		})
		.catch((e) => {
			console.log(e);
		});
};
onMounted(() => {
	initMap();
});

onUnmounted(() => {
	map?.destroy();
});

defineExpose({
	getCoord,
});
</script>
<style scoped>
#container {
	width: 100%;
	height: 400px;
}
</style>
